package com.example.demo.com.java8.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author chengfei5
 * @date 2018/8/21
 */
public class ForkJoinCalculate extends RecursiveTask<Long>{
    private static final long serialVersionUID = -41598011931506130L;

    private long start;
    private long end;

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    private static final long THRESHOLD = 10000;
    @Override
    protected Long compute() {
        long length = end-start;
        //拆分临界值
        if(length <= THRESHOLD){
            long sum = 0;
            for(long i = start;i<=end;i++){
                sum +=i;
            }
            return sum;
        }else{
            long middle = (start+end)/2;
            //递归拆分
            ForkJoinCalculate left = new ForkJoinCalculate(start,middle);
            left.fork();
            ForkJoinCalculate right = new ForkJoinCalculate(middle+1,end);
            right.fork();
            return left.join()+right.join();
        }
    }
}
